<?php
/**
 * Powered By ThinkPHP 5.0.12
 * Copyright (c) 2017 http://www.bojuwang.net All rights reserved.
 * Created by PhpStorm.
 * Date: 2018/4/24 0024
 * Time: 上午 11:52
 * Author: NanTao <260053530@qq.com>
 */

namespace app\admin\controller;
use think\Db;
class Finance extends AdminBasic
{
	 public function getRatio ($sell)
    {
		$ratio = Db::name('admin_ratio')->select();
		$maxRatio = Db::name('admin_ratio')->order('min desc')->value('ratio');
		$minRatio = Db::name('admin_ratio')->order('min asc')->value('ratio');
		foreach ($ratio as $key => $v) {
			if (($sell >= $v['min']) && ($sell < $v['max'])) {
				$return = $v['ratio'];
			}
			if (($sell >= $v['min']) && ($v['max'] == 0)) {
				$return = $maxRatio;
			}
			if (($sell < $v['max']) && ($v['min'] == 0)) {
				$return = $minRatio;
			}

		}

		return $return;
    }
    public function cash()
    {
        $status = input('param.status');
        $keywords = input('param.keywords');
        $logmin = input('param.logmin');
        $logmax = input('param.logmax');
        if (isset($status) && $status != '')
        {
            $where['a.status'] = $status;
            $this->assign('status',$status);
        }
        $keywords ? $where['b.user_name'] = ['like',"%{$keywords}%"] :'';
        $logmin ? $where['a.add_time'] = ['>',$logmin] :'';
        $logmax ? $where['a.add_time'] = ['<',$logmax] :'';
        $list = Db::name('user_cash')->alias('a')->field('a.*,b.user_nickname,b.true_name')->join('user b','a.user_id=b.id')->where($where)->order('a.add_time desc')->paginate(15,false,['query'=>request()->param()]);
        $this->assign('list',$list);

        $money = Db::name('user_cash')->alias('a')->join('user b','a.user_id=b.id')->where($where)->sum('a.money');
        $cost = Db::name('user_cash')->alias('a')->join('user b','a.user_id=b.id')->where($where)->sum('a.cash_cost');
        $tax = Db::name('user_cash')->alias('a')->join('user b','a.user_id=b.id')->where($where)->sum('a.cash_tax');
        $cashMoney = Db::name('user_cash')->alias('a')->join('user b','a.user_id=b.id')->where($where)->sum('a.cash_money');
        $this->assign('money',$money);
        $this->assign('cost',$cost);
        $this->assign('tax',$tax);
        $this->assign('cashMoney',$cashMoney);
        return $this->fetch();
    }
    public function del()
    {
        $cashId = input('param.cashId');
        if (Db::name('user_cash')->delete($cashId))
        {
            json_msg(0,'删除成功');
        }
    }
    public function make()
    {
        $action = input('param.action');
        $cashId = input('param.cashId');
        $cash = Db::name('user_cash')->find($cashId);
        switch ($action){
            case 'success':
                Db::name('user')->where('id',$cash['user_id'])->setDec('frozen',$cash['money']);
                $result = Db::name('user_cash')->where('id',$cashId)->setField('status',1);
                break;
            case 'fail':
                Db::name('user')->where('id',$cash['user_id'])->setInc('balance',$cash['money']);

                post_user_balance_log($cash['user_id'],'+',$cash['money'],"申请提现失败,退回".$cash['money']."元",4,$cashId);
                $result = Db::name('user_cash')->where('id',$cashId)->setField('status',2);
                break;
        }
        if ($result || $result==0)
        {
            json_msg(0,'操作成功');
        } else {
            json_msg(1,'操作失败');
        }
    }
    /*购买记录*/
    public function buy()
    {
        $where = ['b.status'=>['gt','0']];
        $keywords = input('param.keywords');
        $logmin = input('param.logmin');
        $logmax = input('param.logmax');
        $goodsId = input('param.goodsId');
        $keywords ? $where['c.user_name|c.true_name|c.user_nickname|a.order_no|a.goods_title'] = ['like',"%{$keywords}%"] :'';
        $logmin ? $where['b.add_time'] = ['>',$logmin] :'';
        $logmax ? $where['b.add_time'] = ['<',$logmax] :'';
        $goodsId ? $where['a.goods_id']= trim($goodsId) : '';

        $list = Db::name('goods_order_detail a')->field('a.*,c.user_nickname nickname,c.true_name,b.add_time')->join('goods_order b','a.order_id=b.id')->join('user c','a.user_id=c.id')->where($where)->order('b.add_time desc')->paginate(15,false,['query'=>request()->param()]);
        $this->assign('list',$list);
        $countSum = Db::name('goods_order_detail a')->field('a.*,c.user_nickname nickname,c.true_name,b.add_time')->join('goods_order b','a.order_id=b.id')->join('user c','a.user_id=c.id')->where($where)->sum('a.goods_count');
        $priceSum = Db::name('goods_order_detail a')->field('a.*,c.user_nickname nickname,c.true_name,b.add_time')->join('goods_order b','a.order_id=b.id')->join('user c','a.user_id=c.id')->where($where)->sum('a.goods_sell_price');
        $this->assign('countSum',$countSum);
        $this->assign('priceSum',$priceSum);

        return $this->fetch();
    }
    /*返佣记录*/
    public function distribution()
    {
        $where = ['b.status'=>['gt','0']];
        $keywords = input('param.keywords');
        $logmin = input('param.logmin');
        $logmax = input('param.logmax');
        $userId = trim(input('param.keywords'));

        $logmin ? $where['b.add_time'] = ['gt',$logmin] :'';
        $logmax ? $where['b.add_time'] = ['lt',$logmax] :'';
        if ($logmin && $logmax) {
            $where['b.add_time'] = ['between',[$logmin,$logmax]];

        }
        $data = $this->getNextUserArray($userId);
        $where['a.user_id'] = ['in',$data];
        $list = Db::name('goods_order_detail a')
                ->field('a.*,c.user_nickname nickname,c.true_name,b.add_time')
                ->join('goods_order b','a.order_id=b.id')
                ->join('user c','a.user_id=c.id')
                ->where($where)->order('b.add_time desc')
                ->paginate(25,false,['query'=>request()->param()]);

 		$this->assign('list',$list);
        $list1 = Db::name('goods_order_detail a')
                ->field('a.*,c.user_nickname nickname,c.true_name,b.add_time')
                ->join('goods_order b','a.order_id=b.id')
                ->join('user c','a.user_id=c.id')
                ->where($where)->order('b.add_time desc')
                ->select();
                $sellSum = '';
            foreach ($list1 as $key => $value) {
                $sellSum += ($value['goods_sell_price'] * $value['goods_count']);
            }

 		$ratio = $this->getRatio($sellSum);
        $this->assign('ratio',$ratio);

 		 $jiangjin = $sellSum * ($ratio/100);
        $this->assign('jiangjin',$jiangjin);
 		$this->assign('distSum',$distSum);
 		$this->assign('sellSum',$sellSum);
       
        return $this->fetch();

    }


   


    public function getNextUserArray ($userId=675) 
    {
		$data = Db::name('user_distribution')->select();
		$ret=$this->reSort($data,$userId);

		// p($ret);
		return $ret;


	}

     public function reSort($data,$userId,$class_layer=1){
        static $ret = array();
        foreach ($data as $k => $v){
            if($v['user_id']==$userId){
                $v['class_layer'] = $class_layer;
                $ret[] = $v['next_user_id'];
                $this->reSort($data,$v['next_user_id'],$class_layer+1);
            }
        }
        return $ret;
    }










	public function getNextUserArray1($userId=675)
	{
		$data = $this->get_user_agent($userId);
		// p($data);
		return $data;
	}


	public function get_user_agent($userId)
	{
	    static $ret = array();
	    $data = $this->get_user_next_agent_data($userId);
	    if ($data) {
	        foreach ($data as $v) {
	            $ret[] = $v['next_user_id'];
	            $this->get_user_agent($v['next_user_id']);
	        }
	    }
	    return $ret;
	}

	/*
	 * 根据用户userId 获取用户的下级信息
	 * */
	public function get_user_next_agent_data($userId)
	{
	    $data = Db::name('user_distribution')->where('user_id',$userId)->select();
	    if ($data) {
	        return $data;
	    } else {
	        return [];
	    }
	}


    public function test ()
    {

            $where = ['b.status'=>['gt',0]];
            $data = Db::name('goods_order_detail a')
                ->field('a.*,c.user_nickname,c.true_name,b.add_time')
                ->join('goods_order b','a.order_id=b.id')
                ->join('user c','a.user_id=c.id')
                ->where($where)->order('b.add_time desc')
                ->select();
            $sum = '';
            foreach ($data as $key => $value) {
                $sum += ($value['goods_sell_price'] * $value['goods_count']);
            }


            echo $sum."<hr>";
            $sellSum = Db::name('goods_order')->alias('b')->where($where)->sum('sum');
            echo $sellSum."<hr>";
    }



}